const express = require('express')
const router = express.Router()
const weatherService = require('../services/weather.service')

// 获取当前地区天气信息
router.get('/current', async (req, res) => {
  try {
    const { region = '北京' } = req.query
    console.log('收到天气查询请求:', {
      path: req.path,
      query: req.query,
      headers: req.headers
    })

    if (!validateRegion(region)) {
      console.log('无效的地区参数:', region)
      return res.status(400).json({
        code: 400,
        message: '无效的地区参数'
      })
    }

    // 调用天气服务获取天气信息
    const data = await weatherService.getRegionalWeather(region)
    console.log('返回天气数据:', data)

    res.json({
      code: 200,
      message: '获取天气信息成功',
      data
    })
  } catch (error) {
    console.error('处理天气请求失败:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '获取天气信息失败'
    })
  }
})

// 获取天气预报
router.get('/forecast', async (req, res) => {
  try {
    const { region = '北京' } = req.query
    console.log('收到天气预报查询请求:', {
      path: req.path,
      query: req.query,
      headers: req.headers
    })

    if (!validateRegion(region)) {
      console.log('无效的地区参数:', region)
      return res.status(400).json({
        code: 400,
        message: '无效的地区参数'
      })
    }

    // 调用天气服务获取天气预报
    const data = await weatherService.getWeatherForecast(region)
    console.log('返回天气预报数据:', data)

    res.json({
      code: 200,
      message: '获取天气预报成功',
      data
    })
  } catch (error) {
    console.error('处理天气预报请求失败:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '获取天气预报失败'
    })
  }
})

// 获取生活指数
router.get('/lifeindex', async (req, res) => {
  try {
    const { region = '北京' } = req.query
    console.log('收到生活指数查询请求:', {
      path: req.path,
      query: req.query,
      headers: req.headers
    })

    if (!validateRegion(region)) {
      console.log('无效的地区参数:', region)
      return res.status(400).json({
        code: 400,
        message: '无效的地区参数'
      })
    }

    // 调用天气服务获取生活指数
    const data = await weatherService.getLifeIndex(region)
    console.log('返回生活指数数据:', data)

    res.json({
      code: 200,
      message: '获取生活指数成功',
      data
    })
  } catch (error) {
    console.error('处理生活指数请求失败:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '获取生活指数失败'
    })
  }
})

// 验证地区参数
function validateRegion(region) {
  return region && typeof region === 'string' && region.length > 0
}

module.exports = router